package com.ruoyi.system.condig;

import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.springframework.stereotype.Component;

import java.util.Properties;

/**
 * MyBatis SQL 拦截器，将 SQL 与当前 @Log 方法关联
 */
@Component
@Intercepts({
        @Signature(type = Executor.class, method = "query",
                args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}),
        @Signature(type = Executor.class, method = "update",
                args = {MappedStatement.class, Object.class})
})
public class SqlMethodAssociateInterceptor implements Interceptor {

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        // 1. 获取 SQL 信息
        MappedStatement ms = (MappedStatement) invocation.getArgs()[0];
        BoundSql boundSql = ms.getBoundSql(invocation.getArgs()[1]);
        String sql = boundSql.getSql().replaceAll("\\s+", " "); // 格式化 SQL
        String operationType = SqlCommandType.SELECT.equals(ms.getSqlCommandType()) ? "SELECT" :
                SqlCommandType.INSERT.equals(ms.getSqlCommandType()) ? "INSERT" :
                        SqlCommandType.UPDATE.equals(ms.getSqlCommandType()) ? "UPDATE" :
                                SqlCommandType.DELETE.equals(ms.getSqlCommandType()) ? "DELETE" : "UNKNOWN";

        // 2. 记录 SQL 执行耗时
        long startTime = System.currentTimeMillis();
        Object result;
        try {
            result = invocation.proceed();
        } finally {
            long costTime = System.currentTimeMillis() - startTime;

            // 3. 将 SQL 信息存入上下文（自动关联当前 @Log 方法）
            MethodSqlContext.SqlLogInfo sqlLog = new MethodSqlContext.SqlLogInfo();
            sqlLog.setSql(sql);
            sqlLog.setOperationType(operationType);
            sqlLog.setExecuteTimeMs(costTime);
            MethodSqlContext.addSql(sqlLog); // 关键：通过 ThreadLocal 关联到当前方法
        }

        return result;
    }

    //@Override
    //public Object plugin(Object target) {
    //    // 只对 Executor 接口生成代理
    //    if (target instanceof Executor) {
    //        return Plugin.wrap(target, this);
    //    }
    //    return target;
    //}
    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {
    }
}